import React, { useState, useRef, useEffect } from 'react';
import { Modal, Form, Select, Row, Col, Input } from 'antd';
import type { DraggableData, DraggableEvent } from 'react-draggable';
import Draggable from 'react-draggable';

interface IProps {
  isModalOpen?: boolean;
  setIsModalOpen: (flag: boolean) => void;
  tableSelectedRows?: any;
}

const { Option } = Select;

const EnableOrDisable: React.FC<IProps> = (props) => {
  const { isModalOpen, tableSelectedRows, setIsModalOpen } = props;

  const [disabled, setDisabled] = useState(false);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const draggleRef = useRef<HTMLDivElement>(null);

  const [form] = Form.useForm();

  // 开始拖拽回调
  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  useEffect(() => {
    if (tableSelectedRows && tableSelectedRows.length !== 0) {
      const tableSelectData = tableSelectedRows[0];
      form.setFieldsValue({
        name: tableSelectData?.name,
      });
    }
  }, [tableSelectedRows]);

  return (
    <Modal
      title={
        <div
          style={{
            width: '100%',
            cursor: 'move',
          }}
          onMouseOver={() => {
            if (disabled) {
              setDisabled(false);
            }
          }}
          onMouseOut={() => {
            setDisabled(true);
          }}
        >
          删除
        </div>
      }
      onOk={handleOk}
      onCancel={handleCancel}
      modalRender={(modal) => (
        <Draggable
          disabled={disabled}
          bounds={bounds}
          onStart={(event, uiData) => onStart(event, uiData)}
        >
          <div ref={draggleRef}>{modal}</div>
        </Draggable>
      )}
      open={isModalOpen}
    >
      <Form
        labelAlign="right"
        labelCol={{ style: { width: 80 } }}
        labelWrap={true}
        form={form}
        name="enableDisable"
        style={{ width: '100%' }}
        initialValues={{ bangdinggong: 'dongjie' }}
      >
        <Form.Item label="登录名" name="name">
          <Input />
        </Form.Item>
        <Form.Item
          label="状态"
          name="bangdinggong"
          rules={[{ required: true }]}
        >
          <Select>
            <Option value="dongjie">冻结</Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default EnableOrDisable;
